<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;

class Shangmengwang extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        return [
            'commodityBranchId' => $bean->getGoodsId(), //商品编码
            'external_orderno'  => $bean->getOrderNo(), //订单号
            'buyCount'          => $bean->getRechargeNum() * $bean->getStartCharging(),//充值数量
            'callbackUrl'       => $bean->getNotifyUrl(), //异步回调地址
            'remark'            => "",
            'externalSellPrice' => $bean->getUnitPrice(),
            'template'          => json_encode([urlencode($bean->getAccount())]),
        ];
    }

    /**
     * @param PendingRequest $http
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return PromiseInterface
     */
    public function recharge(PendingRequest $http, InterfaceConfiguration $config, BasicInformation $bean): PromiseInterface
    {
        $data = $this->rechargeData($bean);
        $sign = $this -> sign($data,$bean -> getSecretKey());
        $url = sprintf("%s?userName=%s&sign=%s", $config->recharge_url, $bean->getSupplierNum(), $sign);
        return $this->httpClient($http)->asJson()->post($url, $data);
    }
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
        return  strtoupper( md5( json_encode($array) . $secret_key));
    }
    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('externalOrderno', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['4', '5']))->setRechargeSuccess($status == '4');
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $sign = strtoupper(md5($bean -> getSecretKey()));
        $url = $config -> balance_url.'?userName='.$bean -> getSupplierNum().'&sign='.$sign;
        $result = file_get_contents($url);
        return data_get(json2array($result), $config->balance_title, 0);
    }
}
